package com.local.order.service.impl;

import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.constants.OrderStatusEnum;
import com.local.common.util.NumberUtil;
import com.local.common.util.PageResultUtil;
import com.local.common.util.ResultUtil;
import com.local.order.mapper.OrderItemMapper;
import com.local.order.mapper.OrderMapper;
import com.local.order.pojo.Order;
import com.local.order.pojo.OrderItem;
import com.local.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 查询列表，支持翻页
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @param isDeleted
     * @return
     */
    @Override
    public PageResultUtil<Order> findOrderList(Integer page, Integer limit, String sort, String order, Integer isDeleted) {
        Integer start = (page - 1) * limit;
        List<Order> orderList = orderMapper.findOrderList(start, limit, sort, order, isDeleted);
        Integer totalOrders = orderMapper.getTotalOrders(isDeleted);
        PageResultUtil<Order> orderPageResultUtil = new PageResultUtil<>(orderList, totalOrders, limit, page);
        return orderPageResultUtil;
    }


    /**
     * 后台修改订单
     * @param order
     * @return
     */
    @Override
    public Integer update(Order order) {
        return orderMapper.update(order);
    }


    /**
     * 批量修改订单状态为：配货完成
     * @param ids
     * @return
     */
    @Override
    public String checkDone(Integer[] ids) {
        List<Order> orderList = orderMapper.selectByIds(ids);
        if (orderList.isEmpty()) {
            return "无法查询到订单";
        }

        List<String> errorOrderNos = new ArrayList<>();
        for (Order order : orderList) {
            //如果订单被删除或不是“已支付”，则不能进行“配货完成”操作
            if (order.getIsDeleted() == 1 || order.getOrderStatus() != 1) {
                errorOrderNos.add(order.getOrderNo());
            }
        }
        if (errorOrderNos.isEmpty()) {
            String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Integer updateResult = orderMapper.updateStatusByIds(ids, OrderStatusEnum.GOODS_READY.getValue(), dateTime);
            if (updateResult > 0) {
                return "";
            } else {
                return "配货完成操作失败，请稍后再试";
            }
        } else {
            return errorOrderNos.toString() + "：以上订单状态不匹配，无法执行配货完成操作，请重新选择";
        }
    }


    /**
     * 批量修改订单状态为：出库
     * @param ids
     * @return
     */
    @Override
    public String checkOut(Integer[] ids) {
        List<Order> orderList = orderMapper.selectByIds(ids);
        if (orderList.isEmpty()) {
            return "无法查询到订单";
        }

        List<String> errorOrderNos = new ArrayList<>();
        for (Order order : orderList) {
            //如果订单被删除或不是“已支付”或“配货完成”，则不能进行“出库完成”操作
            if (order.getIsDeleted() == 1 || (order.getOrderStatus() != 1 && order.getOrderStatus() != 2)) {
                errorOrderNos.add(order.getOrderNo());
            }
        }
        if (errorOrderNos.isEmpty()) {
            String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Integer updateResult = orderMapper.updateStatusByIds(ids, OrderStatusEnum.GOODS_DELIVER.getValue(), dateTime);
            if (updateResult > 0) {
                return "";
            } else {
                return "出库操作失败，请稍后再试";
            }
        } else {
            return errorOrderNos.toString() + "：以上订单状态不匹配，无法执行出库完成操作，请重新选择";
        }
    }


    /**
     * 批量修改订单状态为：商家关闭
     * @param ids
     * @return
     */
    @Override
    public String close(Integer[] ids) {
        List<Order> orderList = orderMapper.selectByIds(ids);
        if (orderList.isEmpty()) {
            return "无法查询到订单";
        }

        List<String> errorOrderNos = new ArrayList<>();
        for (Order order : orderList) {
            //如果订单被删除或已关闭或者已完成，则不能进行“商家关闭”操作
            if (order.getIsDeleted() == 1 || order.getOrderStatus() == 4 || order.getOrderStatus() < 0) {
                errorOrderNos.add(order.getOrderNo());
            }
        }
        if (errorOrderNos.isEmpty()) {
            String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            Integer updateResult = orderMapper.updateStatusByIds(ids, OrderStatusEnum.CLOSE_BUSINESS.getValue(), dateTime);
            if (updateResult > 0) {
                return "";
            } else {
                return "关闭操作失败，请稍后再试";
            }
        } else {
            return errorOrderNos.toString() + "：以上订单状态不匹配，无法执行关闭订单操作，请重新选择";
        }
    }


    /**
     * 生成新订单
     * @param order
     * @return
     */
    @Override
    public ResultUtil<Order> saveOrder(Order order) {
        Integer userId = order.getUserId();
        String address = order.getUserAddress();
        Integer priceTotal = order.getTotalPrice();
        //生成随机的订单号
        String orderNo = NumberUtil.genOrderNo();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setUserAddress(address);
        order.setTotalPrice(priceTotal);
        order.setExtraInfo("支付宝沙箱支付");
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        order.setCreateTime(dateTime);
        order.setUpdateTime(dateTime);
        Integer saveResult = orderMapper.save(order);
        if (saveResult > 0) {
            return new ResultUtil(200, "", order);
        } else {
            return new ResultUtil(201, "订单生成失败，请稍后再试", order);
        }
    }


    @Override
    public Order getByOrderNo(String orderNo) {
        Order order = orderMapper.getByOrderNo(orderNo);
        if (Objects.nonNull(order)) {
            List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getOrderId());
            order.setOrderItemList(orderItems);
        }
        return order;
    }

    /**
     * 将超时（30分钟）未支付的订单关闭
     * @param orderId
     * @return
     */
    @Override
    public Integer timeOutClose(Integer orderId) {
        Integer[] ids = {orderId};
        Integer orderStatus = OrderStatusEnum.CLOSE_TIMEOUT.getValue();
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return orderMapper.updateStatusByIds(ids, orderStatus, dateTime);
    }


    /**
     * 查询用户的订单列表，包含订单的商品
     * @param userId
     * @param page
     * @param limit
     * @param isDeleted
     * @return
     */
    @Override
    public PageResultUtil<Order> findUserOrderItemList(Integer userId, Integer page, Integer limit, Integer isDeleted) {
        Integer start = (page - 1) * page;
        List<Order> userOrderList = orderMapper.findUserOrderList(userId, start, limit, isDeleted);
        for (Order order : userOrderList) {
            Integer orderId = order.getOrderId();
            List<OrderItem> orderItemList = orderItemMapper.selectByOrderId(orderId);
            order.setOrderItemList(orderItemList);

            order.setOrderStatusString(OrderStatusEnum.getOrderStatusEnumByStatus(order.getOrderStatus()).getName());
        }

        Integer totalUserOrder = orderMapper.getTotalUserOrder(userId, isDeleted);

        PageResultUtil<Order> pageResultUtil = new PageResultUtil<>(userOrderList, totalUserOrder, limit, page);
        return pageResultUtil;
    }
}
